// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var router = require("../hash/pageRouter");
	var dialog = require("dialog");
	var validate = require("validate");
	var databind = require("databind");
	var css_detail_info = require("./financingDetailInfo.css");
	var html_financingDetail_Cancel = require("./financingDetail_Cancel.html");
	var html_financingDetail_submit = require("./financingDetail_submit.html");
	var html_financingDetail_financeContract = require("./financingDetail_financeContract.html");
	var html_financingDetail_supervisionContract = require("./financingDetail_supervisionContract.html");
	var html_financingDetail_supervisionInform = require("./financingDetail_supervisionInform.html");
	var html_financingDetail_loanNotice = require("./financingDetail_loanNotice.html");
	var html_financingDetail_signDelivery = require("./financingDetail_signDelivery.html");
	var html_financing_adjust = require("./html_financing_adjust.html");
	var html_financing_replenish = require("./html_financing_replenish.html");
	var html_financing_adjust1 = require("./html_financing_adjust1.html");
	var html_financingDetail_recieveNotice = require("./financingDetail_recieveNotice.html");
	var html_coldStorage = require("./html_coldStorage.html");
	var html_financeWaybill = require("./html_financeWaybill.html");
	var html_cutLines = require("./html_cutLines.html");
	var constant = require("constant");
	var html_bailReturn = require("./html_bailReturn.html");
	var tools = require("tools");
	var pageIndex = 1,
		pageSize = 10,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var financeId = "";
	var enterpriseId = "";
	var financeType = "";
	var financeNumber = "";
	var dataFinancingDetail;
	var financeState;
	var storage = window.sessionStorage;
	var init = function(page) {
		$("#financeApplicationList").remove();
		financeId = page.params.financeId || base.getUrlParam("financeId");
		initFinancingDetail(financeId);
		initEvent();
		router.init();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}

		//企业详情
		$(".tab1").on("click", ".enterpriseDetail", function() {
			//			router.route("client/clientManage_details.html?enterpriseId=" + enterpriseId, true);
			storage.setItem("enterpriseId", enterpriseId);
			window.open("../client/clientManageDetailIntact.html");
		});

		//调整记录
		$(".tab1").on("click", ".financingAdjustRecord", function() {
			router.route("financing/adjustCreditRecord.html?financeId=" + financeId, true);
		});
		//费用信息
		$(".tabl").on("click","financingcost",function(){
			router.route("financing/information.html?financeId="+financeId,true);
		});

		//追加记录
		$(".tab1").on("click", ".depositAdjustRecord", function() {
			router.route("financing/adjustdepositRecord.html?financeId=" + financeId, true);
		});
		
		//投保
		$(".tab1").on("click", "#insure", function() {
			router.route("insuranceManage/createInsurance.html?financeId=" + financeId);
		});

		//完成融资项目
		$(".platformBtns").on("click", ".button-submit-supervisionEndall", function() {
			dialog.showDialog($("#supervisionEndall_dialog"), function() {});
			databind.fillForm($("#supervisionEndall_dialog"), {
				financeId: financeId
			});
			$("#sure_supervisionEndall").on("click", function() {
				databind.submitDom($(".supervisionEndallContent"), function() {
					base.alert(1, "成功完成融资");
					router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
					dialog.hideDialog($("#supervisionEndall_dialog"));
				});
			});
		});
		//查看签收单
		$(".platformBtns").on("click", ".button-submit-signDelivery", function() {
			router.route("financing/financingDetail_signDelivery.html?financeId=" + financeId, true);

		});

		$(".platformBtns").on("click", ".button_cancel", function() {
			$("#popdialog").html(html_financingDetail_Cancel);
			var financingDetail_dialog = $("#financingDetail_dialog");
			dialog.showDialog(financingDetail_dialog, function() {});
			rejectFinanceApplication();
		});

		//放款通知
		$(".platformBtns").on("click", ".button-submit-LoanNotice", function() {
			$("#popdialog").html(html_financingDetail_loanNotice);
			var loanNotice_dialog = $("#loanNotice_dialog");
			dialog.showDialog(loanNotice_dialog, function() {});
			databind.fillForm($("#loanNotice_dialog"), {
				financeId: financeId,
				financeNumber: financeNumber
			});
			//放款通知--点击确定提交
			$("#sure_yes_loanNotice").on("click", function() {
				databind.submitDom($(".dialogContent-loanNotice"), function() {
					base.alert(1, "下达放款通知成功");
					router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
					dialog.hideDialog($("#loanNotice_dialog"));
				});
			});
		});

		//点击融资合同
		$(".platformBtns").on("click", ".submit-financeContract", function() { //submit-supervisionContract
			$("#popdialog").html(html_financingDetail_financeContract);
			var financeContract_dialog = $("#financeContract_dialog");
			dialog.showDialog(financeContract_dialog, function() {});
			//上传附件
			$("#uploadFile1024").on('change', function() {
				uploadFile();
			});
			inquireFinanceContract();
			$(".uploadImgP").on("click", ".closeLayer", function() {
				$(this).parent().remove();
				saveMaterials();
			});
			$("#sure_yes").on("click", function() {
				var financeContractIdVar = $("#financeContractId").val();
				if (financeContractIdVar.length == 0) {
					createFinanceContract();
				} else {
					updateFinanceContract();
				}
			});
		});

		//点击监管合同
		$(".platformBtns").on("click", ".submit-supervisionContract", function() { //submit-supervisionContract
			$("#popdialog").html(html_financingDetail_supervisionContract);
			var supervisionContract_dialog = $("#supervisionContract_dialog");
			dialog.showDialog(supervisionContract_dialog, function() {});
			loadLogisticsCompanyPageList("supervisionCompanyName", "supervisionTpl");
			//上传附件
			$("#uploadFile1024").on('change', function() {
				uploadFile();
			});
			inquireFinanceSupervisionContract();
			$(".uploadImgP").on("click", ".closeLayer", function() {
				$(this).parent().remove();
				saveMaterials();
			});

			$("#sure_yes").on("click", function() {
				var supervisionContractId = $("#supervisionContractId").val();
				if (supervisionContractId.length == 0) {
					createSupervisionContract();
				} else {
					updateSupervisionContract();
				}
			});

		});

		$(".platformBtns").on("click", ".button-submit", function() {

			$("#popdialog").html(html_financingDetail_submit);
			var financingDetail_dialog = $("#financingDetail_submit_dialog");
			dialog.showDialog(financingDetail_dialog, function() {});
			databind.fillForm(".dialogContent_submit", {
				financeNumber: financeNumber,
				financeId: financeId
			});
			if (financeType == 1) {
				$(".barter").css("display", "none");
				$(".remark").css("display", "none");
			} else {
				$(".barter").css("display", "inline");
				$(".remark").css("display", "inline");
				$(".order_status").css("background-color", "#28BF85");

			}
			consentFinanceListApplication();
		});

		//点击融资申请基本信息
		$(".financeDetailInfo").on("click", function() {
			router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
		});

		//点击证明材料
		$(".evidentiaryCategorys").on("click", function() {
			router.route("financing/financingDetailEvidentiaryCategorys.html?financeId=" + financeId, true);
		});

		//点击融资动态
		$(".financingDetailDynamic").on("click", function() {
			router.route("financing/financingDetailDynamic.html?financeId=" + financeId + "&financeState=" + financeState, true);
		});

		//checkSupervisionNotice查看监管通知
		$(".platformBtns").on("click", ".checkSupervisionNotice", function() {
			showSupervisionNotice(dataFinancingDetail);
			databind.disableInput($("#supervisionInform_dialog"));
			$("#sure_yes").remove();
		});

		//下发运输通知button-submit-transportNotice
		$(".platformBtns").on("click", ".button-submit-transportNotice", function() {
			dialog.showDialog($("#transportNotice_dialog"), function() {});
			databind.fillForm($("#transportNotice_dialog"), {
				financeId: financeId,
				financeNumber: financeNumber
			});
			loadLogisticsCompanyPageList("transportCompanyName", "transportCompanyTpl");
			showInventory();

		});

		//点击下发运输通知提交按钮
		$("#transportNotice_dialog").on("click", "#sure_transportNotice", function() {
			var inventoryIds = [];
			$.each($(".inventoryId:checked"), function(i, val) {
				inventoryIds[i] = val.value;
			});
			if (inventoryIds.length == 0) {
				base.alert(2, "请勾选货物再下达运输通知单！");
				return;
			}
			var logisticsCompanyName = $(".supervisionCompanyNameInput").val();
			var logisticsCompanyId = $("#transportCompanyName").val();
			var noticeRemark = $("#noticeRemark").val();
			base.fnAjax({
				action: "createTransportNotice.json",
				oData: {
					financeId: financeId,
					financeNumber: financeNumber,
					noticeRemark: noticeRemark,
					logisticsCompanyId: logisticsCompanyId,
					logisticsCompanyName: logisticsCompanyName,
					inventoryId: inventoryIds
				}, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {
						base.alert(1, "下达运输通知成功");
						router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
					} else {
						base.alert(2, "信息获取失败");
					}
				}
			});

		});

		//点击确认监管button-submit-sureSupervision
		$(".platformBtns").on("click", ".button-submit-sureSupervision", function() {

			router.route("financing/sure_deliveryAndsureSupervision.html?financeId=" + financeId, true);

		});

		//点击显示提单号
		$(".platformBtns").on("click", ".button-submit-financeWaybill", function() {
			$("#popdialog").html(html_financeWaybill);
			dialog.showDialog($("#financeWaybill_dialog"), function() {});
			databind.fillForm($("#financeWaybill_dialog"), {
				financeId: financeId
			});
			inquireFinanceWaybillList();
			//点击保存运单号
			$("#financeWaybill_dialog").on("click", ".sure_save", function() {
				databind.submitDom($(".financeWaybillContent"), function() {
					base.alert(1, "保存运单号成功");
					dialog.hideDialog($("#financeWaybill_dialog"));
				});

			});

			//点击添加提单
			$("#financeWaybill_dialog").on("click", "#add_FinanceWaybill", function() {
				var text = '<span for="" class="field-lab2 financing_field-lab2 position" style="margin-left: 30px;"> 运单号：';
				text += '<input class="field-input " codeName="运单号"  placeholder="请输入运单号" isNull="1" minLength="1" maxLength="255" type="text" name="waybillNumber" /><a class="closeLayer"></a>';
				text += '</span>';
				$("#waybillNumberP").append(text);
			});

			//点击删除提单
			$("#financeWaybill_dialog").on("click", ".closeLayer", function() {
				$(this).parent().remove();
			});
			
			//校验订舱箱量
			$("#financeWaybill_dialog").on("change", "input[name='caseQuantity']", function() {
				if(isNaN($(this).val()) || !(parseFloat($(this).val())%1 === 0)) {
					base.alert(2, "订舱总箱量应为整数");
				}
			});
		});

		//点击监管通知
		$(".platformBtns").on("click", ".button-submit-supervision", function() {
			if (financeState != 0 && financeState != 1 && financeState != 2 && financeState != 3 && financeState != 17) {
				showSupervisionNotice(dataFinancingDetail);
			} else {
				base.alert(2, "请先签订监管合同和融资合同");
			}
		});

		//点击收货通知
		$(".platformBtns").on("click", ".button-submit-recieveNotice", function() {
			base.fnAjax({
				action: "inquireFinanceSupervisionNotice.json",
				oData: {
					financeId: financeId
				}, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {

						if (data.datas.length > 0 && data.datas[0].supervisionNoticeId != 0) {
							initRecieveNoticeDialog();
							showCreateRecieveNotice();
						} else {
							base.alert(2, "请先下达监管合同通知");

						}

					} else {
						base.alert(2, "信息获取失败");
					}
				}
			});
		});
	};

	//查询产品详情
	var inquireFinanceProductDetail = function(productId) {
		var bailRate = 0;
		base.fnAjax({
			action: "inquireFinanceProductDetail.json",
			async: false,
			oData: {
				productId: productId
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					bailRate = data.datas[0].bailRate;
				} else {
					base.alert(2, "数据获取失败");
				}
			}
		});
		return bailRate;
	};

	//查询融资信息的提单号
	var inquireFinanceWaybillList = function() {
			base.fnAjax({
				action: "inquireFinanceWaybillList.json",
				async: true,
				oData: {
					financeId: financeId
				}, //传递参数
				fnSuccess: function(data) { //成功回调
					if (data.status == 200) {
						var tpl;

						if (data.datas.length > 0) {
							tpl = $("#WaybillContent1").html();
							var html = juicer(tpl, data);
							$(".WaybillContent").html(html);
						} else {
							tpl = $("#WaybillContent").html();
							$(".WaybillContent").html(tpl);
						}

						databind.fillForm($(".WaybillContent"), {
							bookingSpaceNumber: dataFinancingDetail.datas[0].bookingSpaceNumber,
							caseQuantity: dataFinancingDetail.datas[0].caseQuantity,
						});
					} else {
						base.alert(3, data.message);
					}
				}
			});
		}
		//显示运输通知--货箱
	var showInventory = function() {
			base.fnAjax({
				action: "inquireWaitTransportNoticeBulkstockInventoryList.json",
				version: "v1.0",
				oData: {
					financeId: financeId
				}, //传递参数
				fnSuccess: function(data) { //成功回调
					if (data.status == 200) {
						var tpl = $("#inventoryTpl").html();
						var html = juicer(tpl, data);
						$("#inventoryBody").html(html);
					} else {
						base.alert(3, data.message);
					}
				}
			});

		}
		//绑定物流公司
	var loadLogisticsCompanyPageList = function(bodyDomId, jsTpl) {
		base.fnAjax({
			action: "inquireLogisticsCompanyListByCompanyName.json",
			version: "v1.0",
			async: false,
			oData: {
				pageIndex: 1,
				pageSize: 50
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					var tpl = $("#" + jsTpl).html();
					var html = juicer(tpl, data);
					$("#" + bodyDomId).html(html);

				} else {
					base.alert(3, data.message);
				}
			}
		});

		//下发运输通知   绑定点击物流方事件
		$("#transportCompanyName").change(function() {

			var companyName = $("#transportCompanyName option:selected").text();
			$(".supervisionCompanyNameInput").val(companyName);
		});

		//绑定点击物流方事件
		$("#supervisionCompanyName").change(function() {

			var companyName = $("#supervisionCompanyName option:selected").text();
			$(".supervisionCompanyNameInput").val(companyName);
		});
	}

	//监管通知获取监管合同和监管物流
	var inquireSupervisionContractToSupervisionNotice = function() {
		base.fnAjax({
			action: "inquireFinanceSupervisionContract.json",
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					databind.fillForm(".supervisionInformContent", data.datas[0]);

				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}

	//判断是创建还是修改监管合同
	var inquireFinanceSupervisionContract = function() {

		base.fnAjax({
			action: "inquireFinanceSupervisionContract.json",
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if (data.datas.length > 0 && data.datas[0].supervisionContractId != 0) {
						databind.fillForm(".supervisionContractContent_submit", data.datas[0]);

						$(".supervisionContractContent_submit").attr("action", "updateSupervisionContract");
						showImg(data.datas[0].materials);
					} else {
						databind.fillForm(".supervisionContractContent_submit", {
							financeNumber: financeNumber,
							financeId: financeId
						});

					}

				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}

	//判断是创建还是修改融资合同
	var inquireFinanceContract = function() {
		base.fnAjax({
			action: "inquireFinanceContract.json",
			oData: {
				financeId: financeId,
				contractType: 1
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if (data.datas.length > 0 && data.datas[0].financeContractId != 0) {
						databind.fillForm(".financeContract", data.datas[0]);
						$(".financeContract").attr("action", "updateFinanceContract");
						showImg(data.datas[0].materials);
					} else {
						databind.fillForm(".financeContract", {
							financeNumber: financeNumber,
							financeId: financeId
						});

					}

				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}

	//显示图片
	var showImg = function(materials) {
		var fileUuids = materials.split(",");
		var html = "";
		var imgSrc = "";
		for (var i = 0; i < fileUuids.length; i++) {
			imgSrc = fileUuids[i];
			if (imgSrc.length != 0) {
				html = '<a target="_Blank" href="/finance/api/1.0/downloadFile.file?fileUuid=' + imgSrc + '">';
				html += '<div class="finance-file" id="' + imgSrc + '">';
				html += '<img  src="../../../res/png/file_icon.png" class="finance-field-img"  alt="' + imgSrc + '" />';
				html += '<a class="closeLayer" ></a><div class="fileName"></div></div></a>';
				$(".uploadImgP").append(html);
			}

		}
	}

	var uploadFile = function() {
		if ($("#uploadFile1024").val() != "") {
			var fileType = "doc,pdf,jpg,png,bmp";
			var prompt = validate.validateFileType($("#uploadFile1024"), fileType);
			if (prompt.length > 1) {
				base.alert(2, prompt);
				return;
			}
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: "uploadFile1024",
				dataType: 'json',
				success: function(data) {
					var imgSrc = "";
					var html = "";
					imgSrc = data.data[0].fileUuid;
					var fileNameStr = data.data[0].fileName;
					var fileNameStrs = fileNameStr.split(".");
					if (fileNameStrs[0].length > 10) {
						fileNameStr = fileNameStrs[0].substr(0, 10);
					}
					var fileName = fileNameStr.split(".");
					html = '<a href="/finance/api/1.0/downloadFile.file?fileUuid=' + imgSrc + '">';
					html += '<div class="finance-file" id="' + imgSrc + '">';
					html += '<img  src="../../../res/png/file_icon.png" class="finance-field-img"  alt="' + imgSrc + '" />';
					html += '<a class="closeLayer" ></a><div class="fileName">' + fileNameStr + "...." + fileNameStrs[1] + '</div></div></a>';
					$(".uploadImgP").append(html);
					saveMaterials();
				},
				complete: function(xml) {
					$("#uploadFile1024").on('change', function() {
						uploadFile();
					});
				},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			base.alert(3, "请选择文件！");
		}
	}

	//更新fileUuuid保存字段
	var saveMaterials = function() {
		var materials = "";
		var number = $(".finance-field-img").length;
		$(".finance-field-img").each(function(i, object) {
			if (i == number - 1) {
				materials += object.alt;
			} else {
				materials += object.alt + ",";
			}

		});
		$("#materials").val(materials);
	}

	//修改监管合同
	var updateSupervisionContract = function() {

		databind.submitDom(".financeContractContent_submit", function(data) {
			base.alert(1, "修改监管合同成功！");
			dialog.hideDialog($("#supervisionContract_dialog"));
			router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
		});
	}

	//创建监管合同
	var createSupervisionContract = function() {

		databind.submitDom(".supervisionContractContent_submit", function(data) {
			databind.fillForm(".supervisionContractContent_submit", {
				supervisionContractId: data.datas[0].supervisionContractId
			});
			databind.fillInput(".supervisionContractContent_submit", {
				action: "inquireSupervisionContractDetail.json",
				version: "v1.0"
			});

			$(".financeContractContent_submit").attr("action", "updateSupervisionContract");
			base.alert(1, "创建监管合同成功！");
			dialog.hideDialog($("#supervisionContract_dialog"));
			router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
		});
	}

	//修改融资合同
	var updateFinanceContract = function() {

		databind.submitDom(".financeContract", function(data) {
			base.alert(1, "修改融资合同成功！");
			dialog.hideDialog($("#financeContract_dialog"));
			router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
		});
	}

	//创建融资合同
	var createFinanceContract = function() {

		databind.submitDom(".financeContract", function(data) {
			databind.fillForm(".financeContract", {
				financeContractId: data.datas[0].financeContractId
			});
			databind.fillInput(".financeContract", {
				action: "inquireFinanceContractDetail.json",
				version: "v1.0"
			});

			$(".financeContract").attr("action", "updateFinanceContract");
			base.alert(1, "创建融资合同成功！");
			dialog.hideDialog($("#financeContract_dialog"));
			router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
		});
	}

	//融资驳回
	var rejectFinanceApplication = function() {

		$("#financeId").val(financeId);
		$("#sure_no").on("click", function() {
			databind.submitDom(".rejectFinanceContent", function() {

				location.href = "../financing/financingManage.html";
			});
		});
	}

	//同意融资申请
	var consentFinanceListApplication = function() {

		$("#financeId").val(financeId);

		$("#sure_yes").on("click", function() {
			databind.submitDom(".dialogContent_submit", function() {
				base.alert(1, "同意融资申请成功");
				dialog.hideDialog($("#financingDetail_submit_dialog"));
				router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
			});
		});
	};

	var initFinancingDetail = function(financeId) {
		base.fnAjax({
			action: "inquireFinanceApplicationDetail.json",
			async: false,
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					juicer.register("formatCurrency", tools.formatCurrency);
					juicer.register("changeMoneyToChinese", tools.changeMoneyToChinese);
					dataFinancingDetail = data;
					//额度调整
					$("#financingDetailInfo").on("click", ".financingAdjust", function() {
						$("#popdialog").html(html_financing_adjust);
						dialog.showDialog($("#financing_adjust_dialog"));
						tools.requireInput($("#financing_adjust_dialog"));
						tools.inquireCommonSelectorList(11, $("#financing_adjust_dialog .adjustReson"));
						databind.fillForm($("#financing_adjust_dialog"), data.datas[0]);

						var tpl = $("#financingAdjustTpl").html();
						var html = juicer(tpl, data);
						$("#financingAdjustTable").html(html);
						var price = 0;
						$.each($(".financingAdjustPrice"), function() {
							var q = $.trim($(this).parents("tr").find(".financingQuantity").html());
							var p = $.trim($(this).val());
							if ($.trim($(this).val()) != "") {
								price += q * p * 1;
							}
						});
						$("#financingAdujustValuation").html(price);
						$("#financingAdujustValuationOld").html(price);
						$("#financingAdujustValuation").parent().find("input").val(price);

						$("#financing_adjust_dialog").on("change", ".financingAdjustPrice", function() {
							var price = 0;
							$.each($(".financingAdjustPrice"), function() {
								var q = $.trim($(this).parents("tr").find(".financingQuantity").html());
								var p = $.trim($(this).val());
								if ($.trim($(this).val()) != "") {
									price += q * p * 1;
								}
							});
							$("#financingAdujustValuation").html(price);
							$("#financingAdujustValuation").parent().find("input").val(price);
						});

						$("#financing_adjust_dialog").on("click", ".sure_no", function() {
							dialog.hideDialog($("#financing_adjust_dialog"));
						});
						$("#financing_adjust_dialog").on("click", ".sure_yes", function() {
							databind.submitDom($("#financing_adjust_dialog"), function() {
								base.alert(1, "单价调整成功！");
								dialog.hideDialog($("#financing_adjust_dialog"));
								router.route("financing/financingDetailInfo.html?financeId=" + financeId);
							});
						});

						$("#financing_adjust_dialog").on("click", ".dynamicLink", function() {
							var bulkstockname = $(this).parents("tr").attr("bulkstockname");
							var specification = $(this).parents("tr").attr("specification");
							window.open("../publicInquire/publicInquireMonitor.html?bulkstockName=" + encodeURI(encodeURI(bulkstockname)) + "&specification=" + encodeURI(encodeURI(specification)));
						});
					});

					$("#financingDetailInfo").on("click", ".button-submit-order", function() {
						createOrderInfo(financeId);
					});
					
					if (data.datas[0].containerBills.length <= 0) {
						$("#financingDetailInfo .button-submit-order").remove();
					}

					//补货
					$("#financingDetailInfo").on("click", ".button-submit-replenish", function() {
						$("#popdialog").html(html_financing_replenish);
						dialog.showDialog($("#financing_replenish_dialog"));
						tools.requireInput($("#financing_replenish_dialog"));
						tools.inquireCommonSelectorList(11, $("#financing_replenish_dialog .adjustReson"));
						databind.fillForm($("#financing_replenish_dialog"), data.datas[0]);
						loadLoanData($("#financing_replenish_dialog .loanNoticeId"));

						var tpl = $("#financingReplenishTpl").html();
						var html = juicer(tpl, data);
						$("#financingReplenishTable").html(html);
						var price = 0;
						$.each($(".financingAdjustPrice"), function() {
							var q = $.trim($(this).parents("tr").attr("weight"));
							var p = $.trim($(this).val());
							if ($.trim($(this).val()) != "") {
								price += q * p * 1;
							}
						});
						$("#financingReplenishValuation").html(price);
						$("#financingReplenishValuation").parent().find("input").val(price);

						$("#financing_replenish_dialog").on("change", ".financingAdjustPrice", function() {
							var price = 0;
							$.each($(".financingAdjustPrice"), function() {
								var q = $.trim($(this).parents("tr").attr("weight"));
								var p = $.trim($(this).val());
								if ($.trim($(this).val()) != "") {
									price += q * p * 1;
								}
							});
							price += $("#financing_replenish_dialog input[name=replenishAmount]").val() * 1;
							$("#financingReplenishValuation").html(price);
							$("#financingReplenishValuation").parent().find("input").val(price);
						});

						$("#financing_replenish_dialog").on("change", "input[name=replenishAmount]", function() {
							var price = 0;
							$.each($(".financingAdjustPrice"), function() {
								var q = $.trim($(this).parents("tr").attr("weight"));
								var p = $.trim($(this).val());
								if ($.trim($(this).val()) != "") {
									price += q * p * 1;
								}
							});
							price += $("#financing_replenish_dialog input[name=replenishAmount]").val() * 1;
							$("#financingReplenishValuation").html(price);
							$("#financingReplenishValuation").parent().find("input").val(price);
						});

						$("#financing_replenish_dialog").on("click", ".sure_no", function() {
							dialog.hideDialog($("#financing_replenish_dialog"));
						});
						$("#financing_replenish_dialog").on("click", ".sure_yes", function() {
							databind.submitDom($("#financing_replenish_dialog"), function() {
								base.alert(1, "创建成功！");
								dialog.hideDialog($("#financing_replenish_dialog"));
								router.route("financing/financingDetailInfo.html?financeId=" + financeId);
							});
						});

						$("#financing_adjust_dialog").on("click", ".dynamicLink", function() {
							var bulkstockname = $(this).parents("tr").attr("bulkstockname");
							var specification = $(this).parents("tr").attr("specification");
							window.open("../publicInquire/publicInquireMonitor.html?bulkstockName=" + encodeURI(encodeURI(bulkstockname)) + "&specification=" + encodeURI(encodeURI(specification)));
						});

					});

					//收息记录
					$("#financingDetailInfo").on("click", ".button-submit-pahase-record", function() {
						router.route("financing/phaseRecordList.html?financeId=" + financeId);
					});

					//收息
					$("#financingDetailInfo").on("click", ".button-submit-pahase", function() {
						router.route("financing/phaseInventoryList.html?financeId=" + financeId);
					});
					
					//货物一览
					$(".button-submit-pahase-showBulkstock").unbind("click").click(function(){
						router.route("bulkstockListing/accountBulkstockListing.html?financeId=" + financeId + "&productType=" + data.datas[0].productType);
					});

					//追加保证金
					$("#financingDetailInfo").on("click", ".depositAdjust", function() {
						$("#popdialog").html(html_financing_adjust1);
						dialog.showDialog($("#financing_adjust_dialog1"));
						tools.requireInput($("#financing_adjust_dialog1"));
						tools.inquireCommonSelectorList(11, $("#financing_adjust_dialog1 .adjustReson"));
						databind.fillForm($("#financing_adjust_dialog1"), data.datas[0]);

						$("#financing_adjust_dialog1").on("click", ".sure_no", function() {
							dialog.hideDialog($("#financing_adjust_dialog1"));
						});
						$("#financing_adjust_dialog1").on("click", ".sure_yes", function() {
							databind.submitDom($("#financing_adjust_dialog1"), function() {
								base.alert(1, "追加成功！");
								dialog.hideDialog($("#financing_adjust_dialog1"));
								router.route("financing/financingDetailInfo.html?financeId=" + financeId);
							});
						});

						$("#financing_adjust_dialog").on("click", ".dynamicLink", function() {
							var bulkstockname = $(this).parents("tr").attr("bulkstockname");
							var specification = $(this).parents("tr").attr("specification");
							window.open("../publicInquire/publicInquireMonitor.html?bulkstockName=" + encodeURI(encodeURI(bulkstockname)) + "&specification=" + encodeURI(encodeURI(specification)));
						});
					});

					if (data.datas[0].productId != null && data.datas[0].productId != 0) {
						data.datas[0].bailRate = inquireFinanceProductDetail(data.datas[0].productId);
					}
					var html;
					var financingDetailData = data.datas[0];
					enterpriseId = financingDetailData.enterpriseId;
					var financingDetail = $("#financingDetail").html();
					juicer.register("getValueByKey", constant.getValueByKey);
					if (financingDetail != undefined) {
						html = juicer(financingDetail, data);
					}
					$(".tab1").html(html);
					financeType = financingDetailData.financeType;
					financeNumber = financingDetailData.financeNumber;
					financeState = financingDetailData.financeState;
					var supervisionNoticeId = financingDetailData.supervisionNoticeId;
					var financeContractId = financingDetailData.financeContractId;
					var supervisionContractId = financingDetailData.supervisionContractId;

					if (financeState < 9) {
						$(".depositAdjust").remove();
					}

					if (financeState == 1) {
						//$(".platformBtns").append('<input type="button" class="button-submit float-right " value="同意融资" />');
						//$(".platformBtns").append('<input type="button" class="button_cancel " value="融资驳回" />');
					} else if (financeState == 2) {
						//$(".platformBtns").append('<input type="button" class="button-submit-undefined float-right" value="额度处置" />');
					} else if (financeState == 3) {
						//$(".button-submit-contract").removeClass("none");
						//showContractButton();
					} else if (financeState == 5) {
						if (supervisionNoticeId != null && supervisionNoticeId != 0) {
							//							$(".platformBtns").append('<input type="button" class="checkSupervisionNotice button-submit-undefined float-right" value="查看监管通知书" />');
							//							$(".platformBtns").append('<input type="button" class="button-submit-recieveNotice  float-right none" value="通知装货" />');
						} else if (financeContractId == null || financeContractId == 0 || supervisionContractId == null || supervisionContractId == 0) {
//							$(".platformBtns").append('<input type="button" class="button-submit-financeWaybill button-submit-undefined float-right" value="保存提单" />');
							//							$(".button-submit-contract").removeClass("none");
							//							showContractButton();
						} else {
							//							$(".platformBtns").append('<input type="button" class="button-submit-supervision  float-right none" value="通知监管" />');
						}
					} else if (financeState == 6) {
//						$(".platformBtns").append('<input type="button" class="button-submit-financeWaybill button-submit-undefined float-right" value="保存提单" />');

					} else if (financeState == 7) {
						//						$(".platformBtns").append('<input type="button" class="button-submit-LoanNotice button-submit-undefined float-right" value="放款通知" />');
						//						$(".platformBtns").append('<input type="button" class="button-submit-sureSupervision button-submit-undefined float-right" value="查看监管确认书" />');
					} else if (financeState == 9) {} else if (financeState == 10) {
						//						$(".platformBtns").append('<input type="button" class="button-submit-undefined float-right" value="提货审批" />');
					} else if (financeState == 11) {} else if (financeState == 12) {
						//						$(".platformBtns").append('<input type="button" class="button-submit-undefined float-right" value="换货审批" />');
					} else if (financeState == 13) {} else if (financeState == 14) {
						//						$(".platformBtns").append('<input type="button" class="button-submit-undefined float-right" value="收款" />');
					} else if (financeState == 15) {
						//							$(".platformBtns").append('<input type="button" class="button-submit-undefined float-right" value="放货" />');
						//							$(".platformBtns").append('<input type="button" class="button-submit-transportNotice button-submit-undefined float-right" value="运输通知" />');
					} else if (financeState == 17) {
						//						$(".platformBtns").append('<input type="button" class="button-submit-signDelivery button-submit-undefined float-right" value="查看签收单" />');
//						$(".platformBtns").append('<input type="button" class="button-submit-supervisionEndall button-submit-undefined float-right" value="完成融资" />');
					} else if (financeState == 18) {
						$(".financingAdjust").remove();
						$("#insure").remove();
					}
					$(".platformBtns").append('<input type="button" class="button-submit-supervisionEndall button-submit-undefined float-right" value="完成融资" />');
					
					if (data.datas[0].bail - data.datas[0].bailAlreadyReturn > 0) {
						$(".platformBtns").append('<input type="button" class="button-submit-bailReturn button-submit-undefined float-right" value="保证金退还" />');
					}
					
					//保证金退还
					$(".button-submit-bailReturn").unbind("click").click(function() {
						var ii = layer.open({
						  title: '保证金退还',
						  type: 1,
						  skin: 'layui-layer-rim', //加上边框
						  area: ['300px', '150px'], //宽高
						  content: html_bailReturn,
						  btn: ['确定', '取消'],
						  yes: function(){
						  	databind.submitDom($(".createBailReturn"), function(){
						  		layer.msg("申请成功！");
						  		layer.close(ii);
						  	});
						  }
						});
						$(".createBailReturn input[name=financeId]").val(financeId);
						tools.clearNoNumAll($(".createBailReturn"));
					});
					
					$(".platformBtns").append('<input type="button" class="button-submit-financeWaybill button-submit-undefined float-right" value="保存提单" />');
					
					if (financeState >= 18) {
						$(".button-submit-pahase").remove();
						$(".button-submit-replenish").remove();
						$(".button-submit-order").remove();
						$("#addInventoryInfo").remove();
					}

					$(".bulkstockQuantitys").unbind("click").click(function() {
						router.route("bulkstockListing/accountBulkstockListing.html?financeId=" + financeId + "&inventoryState=" + $(this).attr("inventoryState"));
					});

					$(".showcoldStorage").unbind("click").click(function() {
						var $this = $(this);
						var ds = [];
						var d = {};
						d.precool = $this.attr("precool");
						d.ptiOk = $this.attr("ptiOk");
						d.plug = $this.attr("plug");
						d.plugType = $this.attr("plugType");
						d.tempUpDown = $this.attr("tempUpDown");
						d.setTemperature = $this.attr("setTemperature");
						d.tempUnit = $this.attr("tempUnit");
						d.tempMax = $this.attr("tempMax");
						d.tempMin = $this.attr("tempMin");
						d.vent = $this.attr("vent");
						d.coolLetter = $this.attr("coolLetter");
						d.coolRemark = $this.attr("coolRemark");
						ds.push(d);
						data.ds = ds;
						$("#popdialog").html(html_coldStorage);
						$("#coldStorage_dialog .dialogTitle").html("冷藏品信息");
						juicer.register("getValueByKey", constant.getValueByKey);
						var tpl = $("#coldStorageTpl").html();
						var html = juicer(tpl, data);
						$("#coldStorageBody").html(html);
						dialog.showDialog($("#coldStorage_dialog"));

						$("#coldStorage_dialog .sure_yes").unbind("click").click(function() {
							dialog.hideDialog($("#coldStorage_dialog"));
						});
					});

					$(".showDangerous").unbind("click").click(function() {
						var $this = $(this);
						var ds = [];
						var d = {};
						d.declaration = $this.attr("declaration");
						d.instructionManual = $this.attr("instructionManual");
						d.dangerousRemark = $this.attr("dangerousRemark");
						d.unNum = $this.attr("unNum");
						d.imdg = $this.attr("imdg");
						ds.push(d);
						data.ds1 = ds;
						$("#popdialog").html(html_coldStorage);
						$("#coldStorage_dialog .dialogTitle").html("危险品信息");
						juicer.register("getValueByKey", constant.getValueByKey);
						var tpl = $("#dangerousTpl").html();
						var html = juicer(tpl, data);
						$("#coldStorageBody").html(html);
						dialog.showDialog($("#coldStorage_dialog"));

						$("#coldStorage_dialog .sure_yes").unbind("click").click(function() {
							dialog.hideDialog($("#coldStorage_dialog"));
						});
					});

					$.each($("#accountDetail table"), function() {
						var $this = $(this);
						if ($this.find("tr").length == 1) {
							$this.remove();
						}
					});

					$("#addInventoryInfo").unbind("click").click(function() {
						var str = '<tr action="createFinanceContainerBill" style="background-color: #FFF;"><td><select name="model"><option value="GP">GP</option><option value="HQ">HQ</option><option value="RH">RH</option></select></td><td><input type="hidden" name="financeId" value="' + financeId + '"/> <select name="dimension"><option value="10">10</option><option value="20">20</option><option value="40">40</option><option value="48">48</option></select></td><td><input readonly="readonly" value="F" name="emptyWeight" type="text"></td><td><input name="quantity" type="text"></td><td><input type="hidden" name="soc" value="0" class="valueInput" /><input class="soc" type="checkbox"></td><td><a class="cancel1">取消</a> <a class="confrim">确定</a></td></tr>';
						$(".containerBillBody").append(str);

						$(".cancel1").unbind("click").click(function() {
							$(this).parents("tr").remove();
						});

						$(".confrim").unbind("click").click(function() {
							databind.submitDom($(this).parents("tr"), function() {
								base.alert(1, "添加成功！");
								router.route("financing/financingDetailInfo.html?financeId=" + financeId);
							});
						});

						$(".soc").unbind("click").click(function() {
							$(this).parent().find(".valueInput").val("true");
						});
					});

					$(".delete").unbind("click").click(function() {
						var containerBillId = $(this).parents("tr").attr("containerBillId");
						dialog.showConfirmDialog("删除融资箱信息", "是否确定删除融资箱信息？", function() {
							deleteFinanceContainerBill(containerBillId);
						});
					});
					
					//下调融资额度
					$("#financingDetailInfo .cutLines").unbind("click").click(function(){
						$("#popdialog").html(html_cutLines);
						tools.inquireCommonSelectorListByName("审批原因", $("#cutLines_dialog .cutReason"));
						databind.fillForm($("#cutLines_dialog"), data.datas[0]);
						dialog.showDialog($("#cutLines_dialog"));
						
						$("#cutLines_dialog .sure_yes").unbind("click").click(function(){
							databind.submitDom($("#cutLines_dialog"), function(){
								base.alert(1, "提交成功！");
								dialog.hideDialog($("#cutLines_dialog"));
							});
						});
						
						$("#cutLines_dialog .sure_no").unbind("click").click(function(){
							dialog.hideDialog($("#cutLines_dialog"));
						});
					});
					
					//下调融资额度记录
					$("#financingDetailInfo .cutLinesRecord").unbind("click").click(function(){
						router.route("financing/cutLinesRecord.html?financeId=" + financeId);
					});


					tools.inquireCurrentOperationList($("#financingDetailInfo"));
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}

	//放款批次下拉框
	var loadLoanData = function(dom) {
		base.fnAjax({
			action: "inquireLoanNoticePageList.json",
			async: false,
			oData: {
				financeId: financeId,
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					$(dom).html("");
					$.each(data.datas, function(i, v) {
						$(dom).append('<option value=' + this.loanNoticeId + '>' + this.createDateTime + '</option>');
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	var showContractButton = function() {
		$(".button-submit-contract").on("mouseenter", function() {
			$(".auditState").css("display", "inline-block");
		});

		$(".auditState").on("mouseleave", function() {
			$(".auditState").css("display", "none");
		});

	}

	var initRecieveNoticeDialog = function() {
		$("#popdialog").html(html_financingDetail_recieveNotice);
		var recieveNotice_dialog = $("#recieveNotice_dialog");
		dialog.showDialog(recieveNotice_dialog, function() {});
		$(".dialogContent-recieveNotice").on("click", ".delete", function() {
			$(this).parent().parent(".trBulkstocks").remove();
		});

		$("#sure_yes").on("click", function() {

			//修改或者新加下发收货通知
			createOrUpdateRecieveNotice();

		});
	}

	//显示收货通知弹出框（新建）
	var showCreateRecieveNotice = function() {
		var html;
		var financingDetail_bulkstock = $("#financingDetail-bulkstock").html();
		if (financingDetail_bulkstock != undefined) {
			html = juicer(financingDetail_bulkstock, dataFinancingDetail.datas[0]);
		}
		$(".recieveNoticeTable").html(html);
		databind.fillForm(".dialogContent-recieveNotice", dataFinancingDetail.datas[0]);
		inquireSupervisionContractToSupervisionNotice();
		loadLogisticsCompanyPageList("supervisionCompanyName", "supervisionTpl");

		$(".recieveNoticeQuantity").unbind("change").change(function() {

			if (parseFloat($(this).val()) > parseFloat($(this).attr("id"))) {
				base.alert(2, "收货数量不能超过实际数量");
			}
		});
	}

	var createOrUpdateRecieveNotice = function() {
			$.each($(".field-input-recieveNotice"), function(i, val) {
				if (val.value == undefined || val.value.length == 0) {
					if (val.name == "caseQuantity") {
						$(this).val(0);
					} else {
						$(this).val(" ");
					}

				}
			});
			databind.submitDom(".dialogContent-recieveNotice", function() {
				base.alert(1, "下发收货通知成功");
				dialog.hideDialog($("#recieveNotice_dialog"));
				router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
			});
		}
		//查询收货通知列表(带新建和修改效果)
	var inquireRecieveNoticePageList = function() {
		base.fnAjax({
			action: "inquireFinanceRecieveNotice.json",
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					databind.fillForm(".dialogContent-recieveNotice", data.datas[0]);
					//添加货物列表
					var html;
					var financingDetail_bulkstock = $("#financingDetail-bulkstock").html();
					if (data.datas.length > 0 && data.datas[0].recieveNoticeId != 0) { //修改收货通知

						$(".dialogContent-recieveNotice").attr("action", "updateRecieveNotice");
						if (financingDetail_bulkstock != undefined) {
							html = juicer(financingDetail_bulkstock, data.datas[0]);
						}
					} else { //新增收货通知
						if (financingDetail_bulkstock != undefined) {
							html = juicer(financingDetail_bulkstock, dataFinancingDetail.datas[0]);
						}
					}
					$(".recieveNoticeTable").html(html);
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}

	//删除融资订舱箱信息
	var deleteFinanceContainerBill = function(containerBillId) {
		base.fnAjax({
			action: "deleteFinanceContainerBill.json",
			oData: {
				containerBillId: containerBillId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "删除成功！");
					router.route("financing/financingDetailInfo.html?financeId=" + financeId);
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}
	
	//订舱
	var createOrderInfo = function(financeId) {
		base.fnAjax({
			action: "createOrderInfo.json",
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "删除成功！");
					router.route("financing/financingDetailInfo.html?financeId=" + financeId);
				} else {
					base.alert(2, data.message);
				}
			}
		});
	}

	//显示监管通知信息页面
	var showSupervisionNotice = function(dataFinancingDetail) {
		$("#popdialog").html(html_financingDetail_supervisionInform);
		var supervisionInform_dialog = $("#supervisionInform_dialog");
		dialog.showDialog(supervisionInform_dialog, function() {});
		var tpl = $("#supervisionInform").html();
		var html = juicer(tpl, dataFinancingDetail);
		$(".supervisionInformContent").html(html);
		inquireSupervisionContractToSupervisionNotice();
		inquireFinanceSupervisionNotice(dataFinancingDetail);

	}

	//查看融资监管通知信息
	var inquireFinanceSupervisionNotice = function(dataFinancingDetail) {
		base.fnAjax({
			action: "inquireFinanceSupervisionNotice.json",
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					databind.fillForm(".supervisionInformContent", dataFinancingDetail.datas[0]);
					if (data.datas.length > 0 && data.datas[0].supervisionNoticeId != 0) {
						databind.fillForm(".supervisionInformContent", data.datas[0]);

						$(".supervisionInformContent").attr("action", "updateSupervisionNotice");
					}

				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
		//监管通知点击确认
		$("#supervisionInform_dialog").on("click", "#sure_yes", function() {
			var supervisionNoticeId = $("#supervisionNoticeId").val();

			if (supervisionNoticeId.length == 0 || supervisionNoticeId == 0) {
				createSupervisionNotice();
			} else {
				updateSupervisionNotice();
			}

		});

	}

	var createSupervisionNotice = function() {
		databind.submitDom(".supervisionInformContent", function(data) {
			databind.fillForm(".supervisionInformContent", {
				supervisionNoticeId: data.datas[0].supervisionNoticeId
			});
			$(".supervisionInformContent").attr("action", "updateSupervisionNotice");
			base.alert(1, "创建监管通知成功");
			dialog.hideDialog($("#supervisionInform_dialog"));
			router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
		});
	}

	var updateSupervisionNotice = function() {
		databind.submitDom(".supervisionInformContent", function() {
			base.alert(1, "修改监管通知成功");
			dialog.hideDialog($("#supervisionInform_dialog"));
			router.route("financing/financingDetailInfo.html?financeId=" + financeId, true);
		});
	}

	return {
		init: init
	};
});